<!DOCTYPE html>
<html>
<head>

    <meta charset="utf-8"/>

    <title>（Socket-IO ）手写板淘客 Demo</title>

    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/2.0.4/css/bootstrap.min.css"
          rel="stylesheet">

    <style>
        body {
            padding: 20px;
        }

        #console {
            height: 400px;
            overflow: auto;
        }

        .username-msg {
            color: orange;
        }

        .connect-msg {
            color: green;
        }

        .disconnect-msg {
            color: red;
        }

        .send-msg {
            color: #888
        }
    </style>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.slim.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>

<body>

<h1>（Socket-IO ）淘客版本 Demo</h1>

<br/>

<div id="console" class="well">
</div>

<form class="well form-inline" onsubmit="return false;">
    <select id="testEvents"></select>
    <input id="testEventVal" class="input-xlarge" style="width: 1000px" type="text"/><br><br>
    <button type="button" class="btn" id="sendLiveEventBtn">发送淘客事件</button>
    <button type="button" class="btn disconnectBtn">断开</button>
</form>
<form class="well form-inline" onsubmit="return false;">
    <button type="button" class="btn" id="clearScreenBtn">清屏</button>
</form>
<br><br><br>
<hr>
<form class="well form-inline" onsubmit="return false;">
    <input id="msg" class="input-xlarge" type="text" placeholder="请输入聊天室内容"/>
    <button type="button" class="btn" id="sendChatMsgBtn">发送聊天室内容</button>
    <button type="button" class="btn disconnectBtn">断开</button>
</form>

<script>

    var userName = 'user' + Math.floor((Math.random() * 1000) + 1);

    let params = {
        reconnectionDelayMax: 10000,  //重连延迟最大值
        query: {
            "token": "W2252L55IkJmCb194lY1LQWNWI9z2LsGA8v5Yp//MZDG1dcUIUZXKFoLSr2cCuKU",
        }
    }

    // var socket = io.connect('https://class.pendo-tech.com/test', params);
    var socket = io.connect('https://taoke.ojbkk.cn/message', params);
    // var socket = io.connect('http://180.123.11.157:19999/message', params);

    socket.on('connect', function (data) {
        output('<span class="connect-msg">客户端已连接到服务器!</span>');
    });

    socket.on('disconnect', function (data) {
        output('<span class="disconnect-msg">客户端已断开连接!</span>');
    });

    socket.on('reconnect', function (data) {
        output('<span class="connect-msg">客户端已重新连接!</span>');
    });

    socket.on('connect_error', function (data) {
        output('<span class="disconnect-msg">连接异常' + JSON.stringify(data) + '!</span>');
    });

    socket.on('handle_error', function (data) {
        output('<span class="disconnect-msg">服务端处理失败' + JSON.stringify(data) + '!</span>');
    });

    //全局事件
    $('.disconnectBtn').click(() => {
        socket.disconnect();
    })
    $('#clearScreenBtn').click(() => {
        $('#console').html("")
    })

    //发送聊天室消息按钮
    $('#sendChatMsgBtn').click(() => {
        var jsonObject = {
            userName: userName,
            message: $('#msg').val()
        };
        socket.emit('chatevent', jsonObject, function (arg1, arg2) {
            output(`<span class="username-msg">收到了服务端响应:</span> ` + JSON.stringify(arg1));
        });
        $('#msg').val('');
    })

    //监听聊天室事件
    socket.on('serverChatEvent', function (data, ackServerCallback) {
        output(`
        <span class="username-msg">聊天室：${data.userName + '：' + data.message}'</span>
          `)
        if (ackServerCallback) {
            ackServerCallback('客户端收到啦！');
        }
    });

    /*---------------------------   客户端事件    -------------------------------*/
    var eventData = {'uname': '测试用户'}
    let testClientEvents = {
        // 'joinRoom': Object.assign({}, eventData, {}),
    }

    let $testEvents = $('#testEvents');
    $testEvents.append('<option>未选择事件</option>')
    for (const event in testClientEvents) {
        $testEvents.append(`<option value='${event}'>${event}</option>`)
    }
    $testEvents.change(() => {
        let eventName = $testEvents.val();
        if (eventName && testClientEvents[eventName]) {
            $('#testEventVal').val(JSON.stringify(testClientEvents[eventName]))
        } else {
            $('#testEventVal').val('')
        }
    })

    //发送淘客事件
    $('#sendLiveEventBtn').click(() => {
        let eventName = $testEvents.val();
        let eventData = $('#testEventVal').val();
        if (eventName && eventData) {
            socket.emit(eventName, JSON.parse(eventData), function (arg1, arg2) {
                output(
                    `<span class="username-msg">收到了“${eventName}”响应:</span> ` + JSON.stringify(arg1))
                console.log(arg1)
            });
        }
    })

    //监听淘客事件
    let testServerEvents = ['message'];
    for (const event of testServerEvents) {
        socket.on(event, function (data) {
            output(`
        <span class="username-msg">淘客${event + '：' + JSON.stringify(data)}'</span>
          `);
        });
    }

    //
    function output(message) {
        var currentTime = "<span class='time'>" + moment().format('HH:mm:ss.SSS') + "</span>";
        var element = $("<div>" + currentTime + " " + message + "</div>");
        $('#console').prepend(element);
    }

</script>

</body>

</html>
